<!-- ERC-物资类型-物资台账种类页面 -->
<template>
  <div>
    <div v-show="isMain" class="equip-wrap-common">
      <!--左侧树形结构 -->
      <div class="equip-tree-wrap">
        <div class="equip-tree-content">
          <px-input v-model="filterText" style="margin-right: 6px" placeholder="请输入关键字搜索" />
          <px-tooltip content="全部收折" placement="top">
            <px-button v-show="isTreeOpen" link type="primary" icon="ChevronUpRectangle" @click="openOrCloseTree('close')" />
          </px-tooltip>
          <px-tooltip content="全部展开" placement="top">
            <px-button v-show="!isTreeOpen" link type="primary" icon="ChevronDownRectangle" @click="openOrCloseTree('open')" />
          </px-tooltip>
          <px-tooltip content="清除选中" placement="top">
            <px-button style="margin-left: 4px" link type="primary" icon="RefreshLeft" @click="resetCheck" />
          </px-tooltip>
        </div>
        <px-scrollbar class="equip-scroll">
          <px-tree
            ref="treeRef"
            :data="treeData"
            :props="{ children: 'children', label: 'name' }"
            default-expand-all
            node-key="id"
            :filter-node-method="filterNode"
            :expand-on-click-node="false"
            highlight-current
            :expanded-keys="expandedKeys"
            @node-click="nodeClick"
          >
            <template #default="{ node }">
              <span style="display: flex; align-items: center; height: 100%" class="custom-tree-node">
                <span>{{ node.label }}</span>
              </span>
            </template>
          </px-tree>
        </px-scrollbar>
      </div>
      <!-- 右侧整体功能 -->
      <div class="equip-table-wrap">
        <!-- 搜索功能 -->
        <px-form class="custom-form-ui equip-form" :model="queryParams" label-position="right" label-width="120px">
          <px-row :gutter="16">
            <px-col :span="6">
              <px-form-item label="存放地块">
                <px-select v-model="queryParams.storeLocation" placeholder="请选择地块" clearable>
                  <px-option v-for="item in facCodeList" :key="item.id" :label="item.name" :value="item.value" />
                </px-select>
              </px-form-item>
            </px-col>
            <px-col :span="6">
              <px-form-item label="物资名称">
                <px-input
                  v-model="queryParams.name"
                  placeholder="请输入名称"
                  maxlength="50"
                  @blur="queryParams.value = $event.target.value.trim()"
                  @keyup.enter="queryTable"
                >
                  <template #suffix>
                    <px-icon style="cursor: pointer" @click="queryTable">
                      <search />
                    </px-icon>
                  </template>
                </px-input>
              </px-form-item>
            </px-col>
            <px-col :span="6">
              <px-form-item label="库存状态">
                <px-select v-model="queryParams.warningStatus" placeholder="请选择" clearable>
                  <px-option v-for="item in warningStatusList" :key="item.id" :label="item.name" :value="item.value" />
                </px-select>
              </px-form-item>
            </px-col>
            <px-col :span="6">
              <px-button type="primary" @click="queryTable">查询</px-button>
              <px-button @click="resetTable">重置</px-button>
            </px-col>
          </px-row>
        </px-form>
        <!-- 按钮功能 -->
        <div class="equip-table-btn">
          <px-button v-has="'ERC_MATERIAL_TYPE_BATCHDOWNLOAD'" type="primary" plain @click="batchDownload">导出</px-button>
        </div>
        <!-- 表格功能 -->
        <px-table
          :row-class-name="getHighlightClass"
          :data="tableData"
          class="equip-table"
          size="small"
          height="calc(101vh - 311px)"
          border
          @selection-change="selectionChange"
        >
          <px-table-column label="序号" min-width="60" align="center" fixed="left">
            <template #default="{ $index }">
              {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
            </template>
          </px-table-column>
          <px-table-column
            v-for="(item, index) in tableColumns"
            :key="index"
            :label="item.label"
            :min-width="item.minWidth"
            :align="item.align"
            :show-overflow-tooltip="item.showOverflowTooltip"
            :fixed="item.fixed"
          >
            <template #default="scope">
              <px-button v-if="item.name" link type="primary" @click="handleView(scope.row)">
                {{ scope.row.name }}
              </px-button>
              <span v-else-if="item.currentStockView">
                <span v-for="(item, index) in scope.row.facDTOList" :key="index">
                  {{ formatUser(item) }}{{ index < scope.row.facDTOList.length - 1 ? ";" : "" }}
                </span>
              </span>
              <span v-else-if="item.warningStatusValue">
                <px-tag
                  v-if="item.warningStatusValue"
                  effect="plain"
                  :style="{
                    cursor: 'pointer',
                    color: `${tagColorList[scope.row.warningStatus]}`,
                    border: `1px solid ${tagBorderColorList[scope.row.warningStatus]}`,
                    backgroundColor: `${tagBgColorList[scope.row.warningStatus]}`
                  }"
                >
                  {{ scope.row.warningStatusValue }}
                </px-tag>
                <span v-else> {{ scope.row.eqpStatusValue || "-" }} </span>
              </span>
              <span v-else-if="item.code">
                <span> {{ scope.row.code }} </span>
              </span>
              <span v-else>{{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}</span>
            </template>
          </px-table-column>
          <px-table-column fixed="right" label="操作" min-width="120" align="center">
            <template #default="scope">
              <px-tooltip content="详情" placement="top">
                <px-button v-has="'ERC_MATERIAL_LEDGER_VIEW'" link type="primary" icon="Tickets" @click="handleView(scope.row)" />
              </px-tooltip>
            </template>
          </px-table-column>
        </px-table>
        <pagination
          v-show="total > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          class="equip-pagination"
          :total="total"
          @pagination="queryTable"
        />
      </div>
    </div>
    <!-- 详情查看页面 -->
    <ViewSparePartsDetail
      :code="codePlus"
      :isMain="isMain"
      :isView="isView"
      :sparePartsId="sparePartsId"
      :rowData="rowData"
      @backMainPage="backMainPage"
    />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ERC_SPAREPARTS_LEDGER"
});
import { queryDictData } from "@/api/common"; //设备状态接口
import { queryToolMaterial, searchTreeMaterial } from "@/api/erc/material";
import { getCurrentInstance, onMounted, reactive, toRefs, watch } from "vue";
import { useRoute } from "vue-router";
import ViewSparePartsDetail from "./components/ViewSparePartsDetail.vue";
const { proxy }: any = getCurrentInstance();
const route = useRoute();
const state = reactive<any>({
  isMain: true, // 主页面true 详情页面false
  isView: true, // 查看true 新增/编辑false
  parentCode: "",
  typeLevel: "", //右侧新增按钮隐藏显示
  filterText: "",
  treeRef: null,
  treeData: [],
  expandedKeys: [],
  isTreeOpen: true,
  TreedialogVisible: false,
  dialogRow: {},
  facCodeList: [],
  warningStatusList: [],
  positionCodeList: [],
  eqpStatusList: [],
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    storeLocation: "",
    name: "",
    code: "",
    storageLocation: ""
  },
  formValue: {
    eqpId: "",
    eqpName: "",
    facCode: "",
    facName: "",
    typeCode: "",
    positionCode: "",
    warningStatus: ""
  },
  treeDataPlus: "",
  tableColumns: [
    { prop: "name", label: "物资名称", minWidth: "176", showOverflowTooltip: true, fixed: "left", name: true },
    { prop: "unit", label: "单位", minWidth: "80", showOverflowTooltip: true },
    { prop: "currentStock", label: "库存总数", minWidth: "80", showOverflowTooltip: true },
    { prop: "currentStockView", label: "库存详情", minWidth: "80", currentStockView: true, showOverflowTooltip: true },
    { prop: "safeStock", label: "安全库存", minWidth: "80", showOverflowTooltip: true },
    { prop: "warningStatusValue", label: "库存状态", minWidth: "80", showOverflowTooltip: true, warningStatusValue: true },
    { prop: "typeNameAll", label: "物资类型", minWidth: "176", showOverflowTooltip: true },
    { prop: "code", label: "物资编码", minWidth: "176", showOverflowTooltip: true, code: true },
    { prop: "brand", label: "品牌", minWidth: "80", showOverflowTooltip: true },
    { prop: "specification", label: "规格型号", minWidth: "80", showOverflowTooltip: true },
    { prop: "remark", label: "备注", minWidth: "150", showOverflowTooltip: true }
  ],
  tableData: [],
  total: 0,
  selectIds: [],
  eqpIdLists: [],
  rowData: {},
  treeDataQuery: {},
  dialogType: "add",
  treeNameType: "",
  treeTypeid: "",
  dialogVisible: false,
  viewDialogVisible: false,
  sparePartsId: "",
  codePlus: ""
});
const {
  isMain,
  isView,
  filterText,
  typeLevel,
  treeRef,
  treeData,
  expandedKeys,
  isTreeOpen,
  facCodeList,
  warningStatusList,
  queryParams,
  tableColumns,
  tableData,
  total,
  selectIds,
  eqpIdLists,
  treeDataQuery,
  sparePartsId,
  codePlus,
  rowData
} = toRefs(state);

const tagColorList = {
  1: "#909399", // 正常
  2: "#ef4444" // 预警
};

const tagBorderColorList = {
  1: "#b7ead9", // 正常
  2: "#fac7c7" // 预警
};

const tagBgColorList = {
  1: "#e8f8f3", // 正常
  2: "#feecec" // 预警
};

// 监视过滤树的值
watch(filterText, val => {
  treeRef.value!.filter(val);
});

// 进入页面时触发
onMounted(() => {
  const { code, warningStatus } = route.query;
  if (code) {
    codePlus.value = code;
    isMain.value = false;
  }
  if (warningStatus) {
    queryParams.value.warningStatus = warningStatus;
  }
  queryTree();
  querySelectList();
  queryTable();
  QueryWarningStatusList();
});

/** 左侧-树形区 **/
// 进入页面加载左侧树
const queryTree = async () => {
  const data: any = await searchTreeMaterial({
    name: ""
  });
  treeData.value = data;
};
// 过滤树数据
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.name.includes(value);
};
const formatUser = item => {
  return `${item.storeLocation}:${item.facCount}`;
};
// 左侧树添加清除选中按钮
const resetCheck = () => {
  filterText.value = "";
  const selectedNodes = document.querySelectorAll(".is-current");
  selectedNodes.forEach(element => {
    element.classList.remove("is-current");
  });
  queryParams.value = {
    pageNum: 1,
    pageSize: 20,
    storeLocation: queryParams.value.storeLocation,
    value: queryParams.value.value,
    positionCode: queryParams.value.positionCode,
    eqpStatus: queryParams.value.eqpStatus
  };
  queryTable();
};
// 点击左侧树节点，获取facCode，查询设备列表
const nodeClick = (data, node) => {
  treeDataQuery.value = data;
  queryParams.value.typeCode = data.path;
  typeLevel.value = data.typeLevel;
  queryTable();
};
// 打开或者关闭树
const openOrCloseTree = type => {
  if (type == "close") {
    isTreeOpen.value = false;
    let nodes = treeRef.value.store._getAllNodes();
    nodes.forEach(item => {
      item.expanded = false;
    });
  } else if (type == "open") {
    isTreeOpen.value = true;
    let nodes = treeRef.value.store._getAllNodes();
    nodes.forEach(item => {
      item.expanded = true;
    });
  }
};

/** 右侧-表格区 **/
// 归属地块下拉框
const querySelectList = async () => {
  //地块
  facCodeList.value = await queryDictData({ typeCode: "HSE_MATERIAL_FAC" });
};
// 查询物资管理列表
const queryTable = async () => {
  const data = await queryToolMaterial({ ...queryParams.value });
  tableData.value = data?.data;
  total.value = data?.total;
};
// 库存状态下拉框
const QueryWarningStatusList = async () => {
  warningStatusList.value = [{ name: "全部", value: "", id: -1 }];
  const params2 = {
    typeCode: "ERC_MATERIAL_WARNING_STATUS"
  };
  const data2 = await queryDictData(params2);
  warningStatusList.value = warningStatusList.value.concat(data2);
};
// 重置筛选条件和物资管理列表
const resetTable = async () => {
  queryParams.value.name = "";
  queryParams.value.code = "";
  queryParams.value.storeLocation = "";
  queryParams.value.warningStatus = "";
  queryParams.value.storageLocation = "";
  queryTable();
};
// 批量导出按钮
const batchDownload = async () => {
  await queryTable();
  const params = queryParams.value;
  proxy.download("post", "/erc/api/v1/material/exportData", params, "物资台账信息.xlsx");
};
// 表格多选框选中-批量导出、批量删除使用
const selectionChange = (val: any) => {
  selectIds.value = [];
  eqpIdLists.value = [];
  val.forEach((item: any) => {
    if (item.id) {
      selectIds.value.push(item.id);
      eqpIdLists.value.push(item.id);
    }
  });
};

// 查看物资管理详情
const handleView = (row: any) => {
  rowData.value = row;
  codePlus.value = row.code;
  sparePartsId.value = row.code;
  isMain.value = false;
  isView.value = true;
};
// 从新增/编辑、详情返回主页面
const backMainPage = () => {
  isMain.value = true;
};
const getHighlightClass = ({ row, rowIndex }) => {
  // 根据条件返回不同的类名
  if (row.warningStatus === "2") {
    return "highlight-red";
  }
  return ""; // 默认没有高亮
};
</script>

<style lang="scss" scoped>
@import url("@/views/erc/scss/table-flex-list.scss");

.custom-tree-node {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
  font-size: 14px;
}

.buttonGroup {
  display: flex;
  margin-right: 8px;
}

:deep(.px-table-fixed-column--left) {
  background-color: rgb(231 91 91);
}

:deep(.px-table .highlight-red) {
  background-color: rgb(254 236 236);

  .px-table__cell {
    background-color: rgb(254 236 236) !important;
  }
}

:deep(.pagination-container) {
  margin-top: 6px;
}
</style>
